import { getToken, setToken, removeToken } from "@/utils/auth";
import { login, getInfo } from "@/api/user";
const state = {
  token: getToken(),
  roles: [], // 用户角色
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
};

const actions = {
  // 采用真实的接口请求
  login({ commit }, userInfo) {
    // 调⽤并处理结果，错误处理已拦截⽆需处理
    return login(userInfo).then((res) => {
      commit("SET_TOKEN", res.data);
      setToken(res.data);
    });
  },
  getInfo({ commit, state }) {
    return getInfo(state.token).then(({ data: roles }) => {
      commit("SET_ROLES", roles);
      return { roles };
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      removeToken();
      resolve();
    });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
